<script setup>
import GoBackAndSearchNav from "@/components/GoBackAndSearchNav.vue";
import OrderMap from "@/views/order/components/OrderMap.vue";
import {onMounted, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import useOrderStore from "@/store/modules/OrderStore.js";
import {showConfirmDialog, showImagePreview} from 'vant';
import 'vant/es/image-preview/style'
import 'vant/es/dialog/style'
import {hideName, hidePhone} from "@/utils/StringUtils.js";
import TailPrice from "@/components/TailPrice.vue";
import {getDateTimeFormatNow} from "@/utils/DateUtils.js";
import {
  CANCEL,
  getOrderStatusMsg,
  WAIT_COMMENT,
  WAIT_DELIVERY,
  WAIT_PAY,
  WAIT_RECEIVE
} from "@/constants/OrderStatus.js";
import {cancelOrderAPI, getAllOrderAPI, payOrderAPI, updateOrderAPI} from "@/api/order.js";
import {COMMENT_ROUTE} from "@/router/routes/order/comment.js";
import {elErrorMessageTip, elSuccessMessageTip} from "@/utils/MessageTipUtils.js";

const route = useRoute()
const router = useRouter()

const order = ref({})
const getOrder = () => {
  const orderStore = useOrderStore()
  const allOrder = orderStore.all
  const orderId = Number.parseInt(route.query.orderId)
  for (let o of allOrder) {
    if (o.id === orderId) {
      order.value = o
      break
    }
  }
}
onMounted(async () => {
  getOrder()
})

const hideInfoShow = ref(false)

// 图片预览
const imgPreview = () => {
  showImagePreview([order.value.productOptionImg]);
}

const onCancelOrder = async () => {
  showConfirmDialog({
    message: '是否确认取消订单'
  }).then(async () => {
    // on confirm
    let res = null
    if (order.value.status === WAIT_PAY) {
      res = await updateOrderAPI(order.value.id, CANCEL)
    } else {
      res = await cancelOrderAPI(order.value.id, CANCEL)
    }
    if (res) {
      useOrderStore().saveAll(await getAllOrderAPI())
      getOrder()
    }
  }).catch(() => {
    // on cancel
  });
}

const onReceiveOrder = async () => {
  showConfirmDialog({
    message: '是否确认收货'
  }).then(async () => {
    // on confirm
    let res = await updateOrderAPI(order.value.id, WAIT_COMMENT)
    if (res) {
      useOrderStore().saveAll(await getAllOrderAPI())
      getOrder()
    }
  }).catch(() => {
    // on cancel
  });
}

const goComment = () => {
  router.push({name: COMMENT_ROUTE, query: {orderId: order.value.id}})
}

const floatPanelVisible = ref(false)
const anchors = ref([window.innerHeight * 0.85])
const newProductOptionId = ref(0)
const onOpenPanel = async () => {
  floatPanelVisible.value = true
}
const onClosePanel = () => {
  floatPanelVisible.value = false
}
const payByWe = ref(false)
const payByAli = ref(false)
const onOpenPayByWe = () => {
  payByWe.value = true
}
const onOpenPayByAli = () => {
  payByAli.value = true
}
const payHandler = async () => {
  const res = await payOrderAPI(order.value.id, WAIT_DELIVERY)
  if (!res.status) {
    elErrorMessageTip(res.msg)
    return
  }
  elSuccessMessageTip("订单支付成功")
  useOrderStore().saveAll(await getAllOrderAPI())
  getOrder()
  onClosePanel()
}
const onClosePayByWe = () => {
  payByWe.value = false
  payHandler()
}
const onClosePayByAli = () => {
  payByAli.value = false
  payHandler()
}
</script>

<template>
  <div class="order-detail pb-16">
    <GoBackAndSearchNav :title="'订单详情'" :placeholder="true"></GoBackAndSearchNav>
    <OrderMap></OrderMap>
    <van-cell-group inset title="订单状态">
      <van-cell title="状态" :value="getOrderStatusMsg(order?.status)"/>
    </van-cell-group>
    <van-cell-group inset title="物流信息">
      <van-cell title="物流单号" :value="order?.logistics"/>
    </van-cell-group>
    <van-cell-group inset title="收货信息">
      <van-cell center title="显示隐藏信息">
        <template #right-icon>
          <van-switch v-model="hideInfoShow" size="20"/>
        </template>
      </van-cell>
      <van-cell title="姓名" :value="hideInfoShow ? order?.name : hideName(order?.name)"/>
      <van-cell title="手机号" :value="hideInfoShow ? order?.phone : hidePhone(order?.phone)"/>
      <van-cell title="地区" :label="order?.province + order?.city + order?.county"/>
      <van-cell title="详细地址" :label="order?.address"/>
    </van-cell-group>
    <van-cell-group inset title="发货信息">
      <van-cell title="地区" :label="order?.delivery"/>
      <van-cell title="详细地址" :label="order?.addressFrom"/>
    </van-cell-group>
    <van-cell-group inset title="商品信息">
      <van-cell class="flex-center" title="商品图片">
        <template #value>
          <div class="flex justify-end items-center">
            <div class="w-12 h-12" @click="imgPreview">
              <img :src="order?.productOptionImg" alt="">
            </div>
          </div>
        </template>
      </van-cell>
      <van-cell title="商品标题" :label="order?.title"/>
      <van-cell title="商品选项名称" :label="order?.productOptionName"/>
      <van-cell class="flex-center" title="单价">
        <template #value>
          <TailPrice :price="order?.productOptionPrice?.toString()" :is-start="false"></TailPrice>
        </template>
      </van-cell>
      <van-cell title="购买数量" :value="order?.num"/>
      <van-cell class="flex-center" title="运费">
        <template #value>
          <TailPrice :price="order?.freight?.toString()" :is-start="false"></TailPrice>
        </template>
      </van-cell>
      <van-cell class="flex-center" title="合计">
        <template #value>
          <TailPrice :price="order?.allPrice?.toString()" :is-start="false"></TailPrice>
        </template>
      </van-cell>
    </van-cell-group>
    <van-cell-group inset title="其他信息">
      <van-cell title="订单创建时间" :value="getDateTimeFormatNow(order?.createTime)"/>
      <van-cell title="订单更新时间" :value="getDateTimeFormatNow(order?.updateTime)"/>
    </van-cell-group>
    <div class="fixed bottom-0 left-0 w-full p-2 bg-white dark:bg-neutral-900 flex justify-end">
      <div class="ml-2" v-if="order?.status === WAIT_PAY || order?.status === WAIT_DELIVERY">
        <van-button
            type="primary" round size="small"
            color="linear-gradient(to right, #d1d5db, #909399cc, #d1d5db)"
            @click="onCancelOrder"
        >取消订单
        </van-button>
      </div>
      <div class="ml-2" v-if="order?.status === WAIT_PAY">
        <van-button
            type="primary" round size="small"
            @click="onOpenPanel"
            color="linear-gradient(to right, #ee0a24, #ff6034, #ee0a24)"
        >支付订单
        </van-button>
      </div>
      <div class="ml-2" v-if="order?.status === WAIT_RECEIVE">
        <van-button
            type="primary" round size="small"
            @click="onReceiveOrder"
            color="linear-gradient(to right, #5f88ff, #1989fa, #5f88ff)"
        >确认收货
        </van-button>
      </div>
      <div class="ml-2" v-if="order?.status === WAIT_COMMENT">
        <van-button
            type="primary" round size="small"
            @click="goComment"
            color="linear-gradient(to right, #1989fa, #17a6f8, #1989fa)"
        >商品评价
        </van-button>
      </div>
    </div>
    <van-overlay :show="floatPanelVisible" @click="onClosePanel" lock-scroll></van-overlay>
    <van-floating-panel
        :content-draggable="true"
        :anchors="anchors"
        v-show="floatPanelVisible"
    >
      <div class="p-2 flex justify-end items-center">
        <div class="mr-4 text-neutral-600 dark:text-gray-200" @click="onClosePanel">
          <span class="iconfont icon-close"></span>
        </div>
      </div>
      <van-cell title="微信支付" is-link @click="onOpenPayByWe"/>
      <van-cell title="支付宝" is-link @click="onOpenPayByAli"/>
      <van-overlay :show="payByWe" @click="onClosePayByWe">
        <div class="w-screen h-screen flex-center">
          <div class="w-56 rounded-2xl overflow-hidden" @click.stop>
            <img class="w-full h-full object-contain" src="@/assets/imgs/PayByWeChat.png" alt="">
          </div>
        </div>
      </van-overlay>
      <van-overlay :show="payByAli" @click="onClosePayByAli">
        <div class="w-screen h-screen flex-center">
          <div class="w-56 rounded-2xl overflow-hidden" @click.stop>
            <img class="w-full h-full object-contain" src="@/assets/imgs/PayByAli.jpg" alt="">
          </div>
        </div>
      </van-overlay>
    </van-floating-panel>
  </div>
</template>

<style scoped lang="scss">

</style>